import {  useState } from 'react';
import req from '@/utils/request';
import { Avatar, Image, Button, message, Modal, Input, Upload, Flex, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const CommentItem = ({ comment ,onCommentdelet }) => {

    const userInfoStorage = localStorage.getItem('userInfo')
    const { tokenValue = '', loginId = '' } = userInfoStorage ? JSON.parse(userInfoStorage) : {}
    const [picList, setPicList] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [content, setContent] = useState('');

    let commentSave = {
        momentId: comment.momentId,
        replyType: 2,
        targetId: comment.id,
        content: content,
        picUrlList: picList.map(item => item.url)
    }

    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        save();
    };
    const save = () => {
        req({
            method: 'post',
            url: '/share/comment/save',
            data: commentSave
        }, '/circle').then(res => {
            if (!res.success) return;
            message.success('回复成功');
            setIsModalOpen(false);
            setContent();
            onCommentUpdate();
        })
    };
    const handleCancel = () => {
        message.warning("评论取消！");
        setIsModalOpen(false);
        setPicList([]);
    };
    const handleChange = ({ file }) => {
        if (file.status === 'done') {
            // 文件上传成功后，可以在这里处理返回的数据
            console.log('File uploaded successfully:', file.name);
            picList.push({ uid: file.uid, name: file.name, status: file.status, url: file.response.data })
        } else if (file.status === 'removed') {
            const newFileList = picList.filter(f => f != file.response.data);
            setPicList(newFileList);
            console.log('File removed:', file.name);
        }
    }
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            <PlusOutlined />
            <div
                style={{
                    marginTop: 4,
                }}
            >
                Upload
            </div>
        </button>
    );

    const cancelDelete = (e) => {
        // console.log(e);
        message.error('您取消了删除');
    };
    const deleteComment = (commentId,momentId) => {
        req(
            {
                method: 'post',
                url: '/share/comment/remove',
                data:
                {
                    id: commentId,
                    replyType: 1
                }
            }, "/circle"
        ).then(res => {
            if (res.data){
                message.success('删除成功!')
                setTimeout(() => {
                    onCommentdelet(momentId)
                }, 500);
            }
        }).catch(err => {
            message.error(err);
        })
    }
    return (
        <div style={{ marginLeft: !comment.rootNode ? "20px" : '0' }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                <Avatar src={comment.avatar} size={32} shape="square" />
                <div style={{ marginLeft: '10px' }}>
                    <span style={{ fontSize: '14px', color: '#ef794f' }}>{comment.userName}</span><br />
                    <span style={{ color: '#999', fontSize: '12px' }}>{comment.createdTime}</span>
                </div>
                <div style={{ marginLeft: 'auto' }}>
                    <Flex wrap gap="small">
                        <Button color="default" variant="outlined" onClick={showModal}>
                            回复
                        </Button>
                        {loginId == comment.userId ?
                            <Popconfirm
                                title="删除"
                                description="您确认删除您的评论吗?"
                                onConfirm={()=>deleteComment(comment.id,comment.momentId)}
                                onCancel={cancelDelete}
                                okText="确认"
                                cancelText="取消"
                            >
                                <Button type="primary" danger >删除</Button>
                            </Popconfirm>
                            : ''}
                    </Flex>

                </div>

            </div>
            <div style={{ backgroundColor: '#f7f9fe', padding: '10px' }}>
                <div>
                    <p>{comment.content}</p>
                </div>
                <div>
                    {comment.picUrlList && comment.picUrlList.map(item1 => (
                        <Image
                            width={100}
                            src={item1}
                            key={item1}
                        />
                    ))}
                </div>
            </div>
            {comment.children && comment.children.length > 0 && (
                <div>
                    {comment.children.map((child, childIndex) => (
                        <CommentItem key={childIndex} comment={child} />
                    ))}
                </div>
            )}
            <Modal title={"回复：" + comment.userName} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <TextArea rows={4} placeholder="输入回复内容" maxLength={6} onChange={e => setContent(e.target.value)} />
                <div style={{ marginTop: '20px' }}></div>
                <Upload
                    name='uploadFile'
                    listType='picture-card'
                    className='avatar-uploader'
                    accept='image/*'
                    showUploadList={true}
                    withCredentials
                    action='/oss/upload'
                    headers={{
                        satoken: tokenValue
                    }}
                    data={{
                        bucket: 'community-club',
                    }}
                    onChange={handleChange}
                >
                    {picList.length >= 3 ? null : uploadButton}
                </Upload>
            </Modal>
        </div>
    );
};

export default CommentItem;